package com.mg.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mg.common.Constants;
import com.mg.dto.PowerAccountDto;
import com.mg.dto.RevenueRecordDto;
import com.mg.dto.SimpleResult;
import com.mg.mapper.ContractMapper;
import com.mg.mapper.PowerAccountMapper;
import com.mg.mapper.RevenueRecordMapper;
import com.mg.mapper.UserMapper;
import com.mg.model.Contract;
import com.mg.model.PowerAccount;
import com.mg.model.RevenueRecord;
import com.mg.model.User;
import com.mg.service.RevenueRecordService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by mg1213 on 2018/3/18.
 */
@Service
public class RevenueRecordServiceImpl implements RevenueRecordService {
    @Autowired
    private RevenueRecordMapper revenueRecordMapper;
    @Autowired
    private PowerAccountMapper powerAccountMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private UserMapper userMapper;

    private Logger logger = LogManager.getLogger(RevenueRecordServiceImpl.class.getName());

    @Override
    public PageInfo<RevenueRecordDto> selectRecordPageInfo(RevenueRecordDto revenueRecordDto, int start, int limit) {
        PageHelper.offsetPage(start, limit);
        List<RevenueRecordDto> resultList = revenueRecordMapper.selectRecordPageInfo(revenueRecordDto);
        PageInfo<RevenueRecordDto> result = new PageInfo<>(resultList);
        return result;
    }

    @Override
    public PageInfo<RevenueRecordDto> selectPageInfo(RevenueRecordDto revenueRecordDto, int start, int limit) {
        PageHelper.offsetPage(start, limit);
        if (revenueRecordDto.getState() != null && Constants.ALL_STRING.equals(revenueRecordDto.getState())) {
            revenueRecordDto.setState(null);
        }
        List<RevenueRecordDto> resultList = revenueRecordMapper.selectPageInfo(revenueRecordDto);
        PageInfo<RevenueRecordDto> result = new PageInfo<>(resultList);
        return result;
    }

    @Override
    public SimpleResult insertRevenueRecord(RevenueRecord record) {
        SimpleResult result = new SimpleResult();
        try {
            record.setCreateTime(new Date());
            if (record.getRevernueTime() == null) {
                record.setRevernueTime(new Date());
            }
            revenueRecordMapper.insert(record);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("新增收益信息失败 系统未知异常");
            logger.error("新增收益信息失败 系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult updateRevenueRecord(RevenueRecord record) {
        SimpleResult result = new SimpleResult();
        try {
            RevenueRecord record1 = new RevenueRecord();
            record1.setId(record.getId());
            record1 = revenueRecordMapper.selectOne(record1);
            if (record1 == null) {
                result.setSuccess(false);
                result.setMsg("该收益信息不存在，请刷新重试！");
            } else {

                record.setUpdateTime(new Date());
                revenueRecordMapper.updateByPrimaryKeySelective(record);
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("更新收益信息失败 系统未知异常");
            logger.error("更新收益信息失败 系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult deleteRevenueRecord(String ids) {
        SimpleResult result = new SimpleResult();
        try {
            String[] idArr = ids.split(",");
            for (String id : idArr) {

                revenueRecordMapper.deleteByPrimaryKey(Long.parseLong(id));
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("删除收益信息失败 系统未知异常");
            logger.error("删除收益信息失败 系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult createRevenueRecord(RevenueRecordDto record) {
        SimpleResult result = new SimpleResult();

        List<PowerAccountDto> powerAccountDtos = powerAccountMapper.selectAllAccount();
        for (PowerAccountDto accountDto : powerAccountDtos) {
            if (accountDto.getContractId().equals(record.getContractId())) {
                BigDecimal moneyProfit = accountDto.getComputingPowerNum().multiply(record.getProfit());
                BigDecimal ethProfit = accountDto.getComputingPowerNum().multiply(record.getEthProfit());
                BigDecimal profit;
                Contract contract = contractMapper.selectByPrimaryKey(accountDto.getContractId());
                BigDecimal moneyManagerCost = BigDecimal.valueOf(0.00);
                BigDecimal ethManagerCost = BigDecimal.valueOf(0.00);
                if (contract.getManagementCost() != null) {
                    moneyManagerCost = moneyProfit.multiply(contract.getManagementCost().divide(BigDecimal.valueOf(100)));
                    ethManagerCost = ethProfit.multiply(contract.getManagementCost().divide(BigDecimal.valueOf(100)));
                }
                moneyProfit = moneyProfit.subtract(moneyManagerCost);
                ethProfit = ethProfit.subtract(ethManagerCost);
                User user = userMapper.selectByPrimaryKey(accountDto.getUserId());
                if (contract == null) {
                    result.setSuccess(false);
                    result.setMsg("合约不存在！");
                    return result;
                }
                if (user == null) {
                    continue;
                }

                BigDecimal money = BigDecimal.valueOf(0.00);
                if (accountDto.getComputingPowerNum() != null && contract.getElectricityFee() != null) {
                    money = accountDto.getComputingPowerNum().multiply(contract.getElectricityFee());
                }

                if (Constants.ETH_PROFIT.equals(accountDto.getRevenueType())) {
                    profit = ethProfit;
                    BigDecimal ethBalance = user.getEthBalance().add(ethProfit);
                    user.setEthBalance(ethBalance);
                    calElectricity(user, money);
                } else {
                    BigDecimal balance = user.getBalance().add(moneyProfit);
                    user.setBalance(balance);
                    calElectricity(user, money);
                    moneyProfit = moneyProfit.subtract(money);
                    profit = moneyProfit;

                }
                user.setUpdateTime(new Date());
                userMapper.updateByPrimaryKeySelective(user);
                RevenueRecord revenueRecord = new RevenueRecord();
                revenueRecord.setRevernueTime(record.getRevernueTime());
                revenueRecord.setCreateTime(new Date());
                revenueRecord.setProfit(profit);
                revenueRecord.setRevenueType(accountDto.getRevenueType());
                revenueRecord.setContractId(record.getContractId());
                revenueRecord.setUserId(accountDto.getUserId());
                revenueRecord.setState("已发放");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = sdf.format(record.getRevernueTime());
                RevenueRecordDto dto = new RevenueRecordDto();
                dto.setStartTime(dateString);
                dto.setUserId(accountDto.getUserId());
                dto.setContractId(accountDto.getContractId());
                List<RevenueRecordDto> revenueRecordDtos = revenueRecordMapper.selectRevenue(dto);
                if (revenueRecordDtos.isEmpty()) {
                    revenueRecordMapper.insert(revenueRecord);
                }
            }
        }
        return result;
    }

    private void calElectricity(User user, BigDecimal money) {
        if (user != null) {
            if (user.getBalance().compareTo(money) > -1) {
                BigDecimal balance = user.getBalance().subtract(money);
                user.setBalance(balance);
            } else {
                BigDecimal electricityFee = user.getElectricityFee().add(money);
                user.setElectricityFee(electricityFee);
            }


        }
    }
}
